package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ThreadPoolTaskExecutor threadPool;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    @Transactional
    public void addTask(Task task) {
        threadPool.execute(() -> {
            // 1.添加任务到数据库中
            Boolean success = addTaskToDb(task);
            if (success) {
                // 2.添加数据库成功，添加任务到redis
                addTaskToCache(task);
            }
        });
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = true;
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        // 删除redis中的数据
        removeTaskFromCache(task);
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Future<Task> future = threadPool.submit(() -> {
            Task task = null;
            String key = ScheduleConstants.TOPIC + type + "_" + priority;
            String task_json = cacheService.lRightPop(key);
            if (StringUtils.isNotEmpty(task_json)) {
                task = JSON.parseObject(task_json, Task.class);
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
            return task;
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 定时从zSet刷新数据到list
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        threadPool.execute(() -> {
            String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
            // 如果拿到锁
            if (StringUtils.isNotEmpty(token)) {
                log.info("未来数据定时刷新---定时任务");
                // 1.使用scan获取所有key
                Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE);
                for (String futureKey : futureKeys) {
                    // 2.通过key获取小于当前时间的任务
                    Set<String> tasks = cacheService.zRange(futureKey, 0, System.currentTimeMillis());
                    if (tasks != null && tasks.size() > 0) {
                        // 3.获取topicKey
                        String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                        // 4.刷新数据
                        cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                        System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
            }
        });
    }

    /**
     * 定时（5分钟）刷新任务到redis
     */
    @Override
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData() {
        // 1.清空任务缓存
        clearCache();
        log.info("数据库数据同步到缓存");
        // 2.从DB中获取所有小于未来5分钟的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskList = taskinfoMapper.selectList(
                Wrappers.<Taskinfo>lambdaQuery().
                        lt(Taskinfo::getExecuteTime, calendar.getTimeInMillis())
        );
        // 3.添加任务到redis
        if (!taskList.isEmpty()) {
            for (Taskinfo taskinfo : taskList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    /**
     * 清除缓存任务
     */
    private void clearCache() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }

    private void removeTaskFromCache(Task task) {
        String keySuffix = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + keySuffix, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + keySuffix, JSON.toJSONString(task));
        }
    }

    private Task updateDb(long taskId, int status) {
        // 删除任务，更新日志
        taskinfoMapper.deleteById(taskId);
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        return task;
    }

    private void addTaskToCache(Task task) {
        String keySuffix = task.getTaskType() + "_" + task.getPriority();
        // 如果小于等于当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + keySuffix, JSON.toJSONString(task));
            // 如果大于当前时间小于预设值（当前时间+5分钟）
        } else if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            cacheService.zAdd(ScheduleConstants.FUTURE + keySuffix, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    private Boolean addTaskToDb(Task task) {
        Boolean flag = true;
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        int infoRows = taskinfoMapper.insert(taskinfo);
        if (infoRows == 0) {
            return !flag;
        }
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, taskinfoLogs);
        taskinfoLogs.setVersion(1);
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
        int logsRows = taskinfoLogsMapper.insert(taskinfoLogs);
        if (logsRows == 0) {
            return !flag;
        }
        task.setTaskId(taskinfoLogs.getTaskId());
        return flag;
    }
}
